package com.jammingpro.blog_system.utils;

import com.jammingpro.blog_system.constant.Constant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.*;

/**
 * JWT令牌工具类
 */
@Slf4j
public class JwtUtils {
    // 超时时间
    private static final long TOKEN_EXPIRATION = 60 * 60 * 1000;
    // 加密秘钥-字符串
    private static final String SCRECT_STR = "agasf54h3gh1bdv8f7fd7j8uyolpgvz2v3qiptyakvjh62/2jWEJKWK6364alfikjeiqpiwrerFK";
    // 加密秘钥
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(SCRECT_STR));

    /**
     * 生成token/令牌
     * @param claims 待加入token信息
     * @return token/令牌
     */
    public static String genToken(Map<String, Object> claims) {
        String token = Jwts.builder().setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + TOKEN_EXPIRATION))
                .signWith(key)
                .compact();
        return token;
    }

    /**
     * 获得解析链
     * @param token 令牌/token
     * @return 解析链
     */
    public static Claims parseToken(String token) {
        JwtParser parser = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;
        try {
            claims = parser.parseClaimsJws(token).getBody();
        }catch (Exception e) {
            log.info("token {} 解析失败...", token);
            return claims;
        }
        return claims;
    }

    /**
     * 从token提取用户id
     * @param token 令牌/token
     * @return 用户id
     */
    public static Integer getIdByToken(String token) {
        Claims claims = parseToken(token);
        if(claims == null) {
            log.info("JwtUtils: claims is null");
            return null;
        }
        Integer id = (Integer) claims.get(Constant.TOKEN_USER_ID);
        if(id == null || id <= 0) {
            log.info("JwtUtils: id is null");
            return null;
        }
        return id;
    }
}
